<template>
  <div class="spu-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap @refresh="getList" style="flex: 1">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" v-if="$authPass('product.spu.createOrUpdate')" @click="show('add')">添加SPU</a-button>
            <a-dropdown @select="handleSelect($event, '导入')" class="dropdown" v-if="$authPass('product.sku.importProducts')">
              <a-button style="margin-left: 5px" class="gray-outline">导入 <icon-down /></a-button>
              <template #content>
                <a-doption value="1" v-if="$authPass('product.sku.importProducts')">导入SKU</a-doption>
                <a-doption value="2">导入SKU属性</a-doption>
                <!-- <a-doption value="2">导入SPU及关联的SKU</a-doption> -->
              </template>
            </a-dropdown>
            <a-dropdown class="dropdown" v-if="$authPass('product.spu.del')">
              <a-button class="gray-outline">批量操作 <icon-down /></a-button>
              <template #content>
                <!-- <a-doption>批量更新产品图片</a-doption>
                <a-doption>更新持有人信息</a-doption>
                <a-doption>合并SKU到SPU中</a-doption> -->
                <a-doption @click.stop="batchDel" v-if="$authPass('product.spu.del')">删除产品</a-doption>
              </template>
            </a-dropdown>
            <div>
              <span>已选：</span>
              <span style="color: #1966ff">{{ selNum }}</span>
            </div>
            <a-button type="text" @click="rowSelList = false">清除已选</a-button>
          </a-space>
        </template>

        <template #headerRight>
          <!-- <a-popover content="导出SPU" style="font-size: 16px">
            <a-button type="text">
              <template #icon>
                <icon-download />
              </template>
            </a-button>
          </a-popover> -->
        </template>

        <template #tableBody>
          <a-spin :loading="loading" :style="{ width: '100%', height: '100%' }">
            <a-scrollbar style="height: 100%; overflow: auto">
              <div class="clearfix" v-if="tableData[0] && !loading">
                <Item type="SPU" v-for="item of tableData" :item="item" @opreate="toOpearte($event, item)" />
              </div>
              <a-empty v-else />
            </a-scrollbar>
          </a-spin>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <SpuAddDetail ref="spuAddDetail" :detail="detail" @save="getList" :categoryOptions="categoryOptions" />
  <SpuEditDetail ref="spuEditDetail" :detail="detail" @save="getList" :categoryOptions="categoryOptions" />
  <ShowSpuDetail ref="showSpuDetail" :detail="detail" />
  <a-image-preview v-model:visible="visible" :src="src" />
  <CommonLogsDialog v-if="showLogDialog" api="pageProductLog" :id="detail.data.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
  <ImportSku url="https://cdn2.selleroa.com/saas/file/138248165001346049.xlsx" uploadType="sku" v-if="showImportPairDialog" :isShow="showImportPairDialog" @closed="showImportPairDialog = false" @success="sizeChange(20)" />
  <ImportProperty v-if="showImportPairDialogPro" :isShow="showImportPairDialogPro" @closed="showImportPairDialogPro = false" @success="sizeChange(20)" />
</template>

<script lang="ts">
  import { reactive, ref, defineComponent, computed } from 'vue'
  import { getCategoryList, getProductSPUList, delProductSPUList, spuPageRelatedForCompanyVer } from '@/api/product'
  import SearchItem from '@/components/searchItem.vue'
  import ShowSearchItem from '@/components/showSearchItem.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import FilterTable from '@/components/TableFilter.vue'
  import Item from './componetns/item.vue'
  import SpuAddDetail from './componetns/addSPu/spudetail.vue'
  import SpuEditDetail from './componetns/editSpu/spudetail.vue'
  import ShowSpuDetail from './componetns/showSpuDetail.vue'
  import { Modal, Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  import _, { values } from 'lodash-es'
  import { getOrganizesUser } from '@/api/system'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import ImportSku from './componetns/importSku.vue'
  import ImportProperty from '../../productSetting/property/componetns/importProperty.vue'
  const dataOptions: any = [
    {
      label: 'SKU',
      value: 'skuList',
    },
    {
      label: 'SPU',
      value: 'spuList',
    },
    {
      label: '产品名称',
      value: 'skuNameList',
    },
  ]

  const rangeShortcuts: any = [
    {
      label: '今天',
      value: () => [dayjs(), dayjs().add(0, 'day')],
    },
    {
      label: '昨天',
      value: () => [dayjs().add(-1, 'day'), dayjs().add(-1, 'day')],
    },
    {
      label: '近三天',
      value: () => [dayjs(), dayjs().add(2, 'day')],
    },
    {
      label: '最近一周',
      value: () => [dayjs(), dayjs().add(6, 'day')],
    },
    {
      label: '最近一个月',
      value: () => [dayjs(), dayjs().add(1, 'month')],
    },
    {
      label: '最近三个月',
      value: () => [dayjs(), dayjs().add(3, 'month')],
    },
  ]
  export default defineComponent({
    name: 'ProductSPU',
    components: { ImportSku, ImportProperty, SearchItem, ShowSearchItem, TableWrap, Item, SpuAddDetail, SpuEditDetail, ShowSpuDetail, FilterTable, CommonLogsDialog },
    setup() {
      let showLogDialog = ref(false)
      let showImportPairDialog = ref(false)
      let showImportPairDialogPro = ref(false)
      let searchValue: any = ref({ timeType: '1', userType: 'developerIdList' })
      let pageNation = reactive({ total: 0, pageSize: 20, pageNum: 1 })
      let visible = ref(false)
      let src = ref('')
      let loading = ref(false)
      let categoryOptions: any = ref()
      let showPopver = ref(false)
      const showSpuDetail = ref()
      const showTagList: any = ref([])
      const tableData: any = ref([])
      const spuAddDetail = ref()
      const spuEditDetail = ref()
      const detail: any = ref({ type: '', data: {} })
      const search = (data: any) => {
        searchValue.value.skuList = ''
        searchValue.value.spuList = ''
        searchValue.value.skuNameList = ''
        searchValue.value[data.code] = data.value
        showPopver.value = false
      }

      const rowSelList = computed({
        set: (val) => {
          tableData.value.map((e: any) => (e.isSel = false))
        },
        get: () => {
          let arr = []
          arr = tableData.value.filter((e: any) => e.isSel)
          return arr
        },
      })

      const filterItem: any = reactive([
        {
          type: 'sel_double',
          key: 'developerId',
          keyItems: [
            { label: '产品开发员', value: 'developerId' },
            { label: '销售员', value: 'salesId' },
          ],
          optionItems: [],
          keyWidth: '120',
          value: ref(),
          placeholder: '请选择',
          label: '产品开发员',
          width: 120,
          isMultiple: false,
        },
        {
          type: 'cascader',
          key: 'categoryIdList',
          optionItems: [],
          keyWidth: '120',
          value: ref(),
          placeholder: '商品分类',
          label: '类目',
          width: 200,
          isMultiple: true,
        },
        {
          type: 'input_keyword_type',
          key: 'sku',
          keyItems: [
            { label: 'SKU', value: 'sku' },
            { label: 'SPU', value: 'spu' },
            { label: '产品名称', value: 'spuName' },
          ],
          keyWidth: '100',
          value: ref(),
          placeholder: '请输入',
          label: 'SKU',
          width: 160,
          isMultiple: true,
        },
        {
          type: 'keyword_date_range',
          key: 'gmtCreate',
          keyItems: [
            { label: '创建日期', value: 'gmtCreate' },
            { label: '更新时间', value: 'gmtWrite' },
          ],
          keyWidth: '110',
          value: ref(),
          placeholder: '请输入',
          label: '创建日期',
          width: 200,
        },
      ])

      const userList: any = ref([])

      const searchTime = () => {
        showPopver.value = false
        console.log(searchValue)
      }
      const delTag = (data: any) => {}
      const changePage = (val: number) => {
        pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        pageNation.pageNum = 1
        pageNation.pageSize = val
        getList()
      }
      const getCategory = async () => {
        const res: any = await getCategoryList()
        filterItem[1].optionItems = res.data
        categoryOptions.value = res.data
      }

      const show = (type: string, data?: any) => {
        detail.value.type = type
        data ? (detail.value.data = data) : (detail.value.data = {})
        spuAddDetail.value.visible = true
      }

      const toOpearte = (type: string, data: any) => {
        switch (type) {
          case 'showImg':
            showImg(data)
            break
          case 'detail':
            showDetail(data)
            break
          case 'edit':
            showEdit(data)
            break
          case 'del':
            showDel('single', data)
            break
          case 'log':
            detail.value.data = data
            showLogDialog.value = true
            break
        }
      }

      // 显示图片
      const showImg = (data: any) => {
        src.value = data.productPicList && data.productPicList[0] ? data.productPicList[0].url : ''
        visible.value = true
      }
      // 查看详情
      const showDetail = (data: any) => {
        detail.value.data = data
        showSpuDetail.value.visible = true
      }
      // 编辑
      const showEdit = (data: any) => {
        detail.value.type = 'edit'
        data ? (detail.value.data = data) : (detail.value.data = {})
        spuEditDetail.value.visible = true
      }
      // 删除
      const showDel = (type: string, data: any) => {
        let params: any = {
          idList: [],
        }

        if (type == 'single') {
          params.idList = new Array(data.id)
        } else {
          params.idList = data.map((e: any) => e.id)
        }

        Modal.error({
          title: '删除确认',
          content: '信息删除后无法恢复，确定要删除吗？',
          titleAlign: 'start',
          cancelText: '取消',
          hideCancel: false,
          onBeforeOk: async (done) => {
            const res: any = await delProductSPUList(params)
            if (res.code == 'SUCCESS') {
              done(true)
              Message.success('删除成功')
              getList()
            }
          },
        })
      }

      const searchByVal = (val: any) => {
        pageNation.pageNum = 1
        searchValue.value = {}
        searchValue.value = val
        if (searchValue.value.startDate) {
          searchValue.value.startDate = `${searchValue.value.startDate} 00:00:00`
          searchValue.value.endDate = `${searchValue.value.endDate} 23:59:59`
        }
        getList()
      }

      const getList = async () => {
        let newValue: any = _.cloneDeep(searchValue.value)

        for (const key in newValue) {
          if (newValue[key] instanceof Array) {
            newValue[key] = newValue[key].join(',')
          }
        }

        delete newValue.timeType
        delete newValue.userType
        loading.value = true
        let params = {
          ...newValue,
          needCount: false,
          pageNum: pageNation.pageNum,
          pageSize: pageNation.pageSize,
        }
        // const res: any = await getProductSPUList(params)
        const res: any = await spuPageRelatedForCompanyVer(params)
        if (res.code == 'SUCCESS') {
          // pageNation.total = res.data.total
          tableData.value = res.data.records
        }
        loading.value = false
        // 获取分页数据
        const res1: any = await spuPageRelatedForCompanyVer({ ...params, needCount: true, pageNum: 1, pageSize: 1 })
        pageNation.total = res1.data.total
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          userList.value = res.data.records
          userList.value.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          filterItem[0].optionItems = userList.value
          console.log(filterItem, 'filterItem')
        }
      }

      const batchDel = async () => {
        if (selNum.value <= 0) {
          return Message.error('请选择需要删除的数据')
        }
        showDel(
          'mul',
          tableData.value.filter((e: any) => e.isSel)
        )
      }

      const selNum = computed(() => {
        let arr = []
        arr = tableData.value.filter((e: any) => e.isSel)
        return arr.length
      })

      const handleSelect = (data: any, type: string) => {
        if (data == 1) {
          showImportPairDialog.value = true
        } else if (data == 2) {
          showImportPairDialogPro.value = true
        }
      }

      getList()
      getCategory()
      getUSerList()
      return {
        src,
        filterItem,
        loading,
        visible,
        getList,
        spuAddDetail,
        showSpuDetail,
        searchValue,
        categoryOptions,
        dataOptions,
        search,
        searchTime,
        showPopver,
        rangeShortcuts,
        delTag,
        showTagList,
        pageNation,
        changePage,
        sizeChange,
        tableData,
        show,
        detail,
        toOpearte,
        searchByVal,
        selNum,
        showLogDialog,
        spuEditDetail,
        batchDel,
        rowSelList,
        handleSelect,
        showImportPairDialog,
        showImportPairDialogPro,
      }
    },
  })
</script>

<style lang="less" scoped>
  .icon-r {
    .arco-icon {
      font-size: 16px;
      color: #000430;
    }
  }

  .arco-scrollbar {
    height: 100%;
    width: 100%;
  }

  .spu-con {
    height: calc(100vh - @menuAndTabHeight);
    width: 100%;
  }

  .body-con {
    width: 100%;
    height: 100%;
    // height: calc(100vh - 310px);
    // width: calc(100vw - 225px);
    padding: 5px;
    box-sizing: border-box;
    overflow: auto;
    // display: flex;
    // justify-content: space-between;
    // flex-wrap: wrap;
  }

  .arco-dropdown-open .arco-icon-down {
    transform: rotate(180deg);
  }
</style>
